<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/3
 * Time: 15:01
 */

namespace backend\models\Service;


use common\models\DAO\Collection;
use common\models\DAO\CollectionAudit;
use common\models\DAO\CollectionDraft;

class CollectionService
{

    static public function collectionCheck($params, $id)
    {
        $return['code'] = 0;
        $return['msg'] = "数据错误";
        $remark = $params['remark'];
        $status = $params['status'];
        $adminID = \Yii::$app->session->get('ADMIN_ID');
        if (!$id) {
            return $return;
        }
        if ($params['id'] != $id) {
            return $return;
        }
        if (!$params['status']) {
            $return['msg'] = "请选择审核状态";
            return $return;
        }

        $cDraft = CollectionDraft::findOne($id);

        if (empty($cDraft)) {
            return $return;
        }

        $cDraft->auditID = $adminID;
        $cDraft->auditTime = time();

        $cAudit = new CollectionAudit();
        $cAudit->cID = $cDraft->id;
        $cAudit->adminID = $adminID;
        $cAudit->auditTime = time();

        if ($status == 2) {
            if (empty($remark)) {
                $return['msg'] = "请填写拒绝原因";
                return $return;
            }
            $cDraft->status = 2;
            if ($cDraft->save()) {
                $cAudit->result = "拒绝";
                $cAudit->remark = $remark;
                if ($cAudit->save()) {
                    return ['code' => 1];
                } else {
                    $return['msg'] = $cAudit->getErrors();
                    return $return;
                }
            } else {
                return $return;
            }
        } elseif ($status == 1) {
            $cDraft->status = $adminID;
            if ($cDraft->save()) {
                $cAudit->result = "通过";
                $cAudit->remark = "";
                if ($cAudit->save()) {
                    $cDraft = $cDraft -> attributes;
                    $Collection = new Collection();
                    $filed = $Collection->attributeLabels();
                    foreach ($cDraft as $key => $value){
                        if(isset($filed[$key]))
                        $Collection -> $key = $value;
                    }
                    if($Collection -> save()){
                        return ['code' => 1];
                    }else{
                        $return['msg'] = $Collection->getErrors();
                        return $return;
                    }
                } else {
                    $return['msg'] = $cAudit->getErrors();
                    return $return;
                }
            } else {
                return $return;
            }
        }
    }

}